<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btnList="fullInfo.btnList"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.baseRef"
              :data="formInfo.data"
              :field-list="formInfo.baseInfoFieldList"
              :label-width="formInfo.labelWidth"
            >
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>报修信息</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.repairRef"
              :data="formInfo.data"
              :field-list="formInfo.repairInfoFieldList"
              :rules="formInfo.repairInfoRules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-assetName>
                <el-input
                  type="input"
                  :disabled="true"
                  class="not-mongolia"
                  placeholder="请选择资产"
                  v-model="formInfo.data.assetName"
                >
                  <template #append>
                    <el-icon @click="openEquipmentWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-faultTime>
                <el-date-picker
                  v-model="formInfo.data.faultTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :disabled-date="faultTimePickerOptions.disabledDate"
                  placeholder="请选择故障发生时间"
                >
                </el-date-picker>
              </template>
              <template v-slot:form-expectCompleteTime>
                <el-date-picker
                  v-model="formInfo.data.expectCompleteTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :disabled-date="expectCompleteTimePickerOptions.disabledDate"
                  placeholder="请选择期望完成时间"
                >
                </el-date-picker>
              </template>

              <template v-slot:form-filePathList>
                <UploadVideo
                  v-model="formInfo.data.filePathList"
                  :action="action"
                  :fileData="formInfo.data.filePathList"
                  @upload="upload"
                />
              </template>
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>派单信息</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.sendOrderRef"
              :data="formInfo.data"
              :field-list="formInfo.sendOrderInfoFieldList"
              :rules="formInfo.sendOrderInfoRules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-dispatchUserName>
                <el-input
                  v-model="formInfo.data.dispatchUserName"
                  type="input"
                  :disabled="true"
                  class="not-mongolia"
                  placeholder="请选择派单人"
                >
                  <template #append>
                    <el-icon @click="openSendOrderUserList"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-acceptUserName>
                <el-input
                  v-model="formInfo.data.acceptUserName"
                  type="input"
                  :disabled="true"
                  class="not-mongolia"
                  placeholder="请选择人员"
                >
                  <template #append>
                    <el-icon @click="openRepairUserWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>

              <template v-slot:form-requireCompleteTime>
                <el-date-picker
                  v-model="formInfo.data.requireCompleteTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择要求完成时间"
                >
                </el-date-picker>
              </template>

              <template v-slot:form-filePathList>
                <UploadVideo
                  v-model="formInfo.data.filePathList"
                  :action="action"
                  @upload="upload"
                />
              </template>
            </page-form>
          </div>
        </div>
      </NewFullScreen>
    </div>

    <!--资产选择-->
    <Select-asset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :highlightRow="true"
      :checkBox="false"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      @callback="callBackAsset"
    />
    <!-- 派单人 -->
    <SelectUsers
      v-if="selectSendOrderInfo.visible"
      v-model:showDialog="selectSendOrderInfo.visible"
      :api="getRrgUserList"
      :saveEmpty="true"
      :query="selectSendOrderInfo.query"
      :check-box="false"
      :highlight-row="true"
      @callback="selectSendOrderCallBack"
    />
    <!-- 维修人员 -->
    <SelectRepairUser
      v-if="selectRepairUserInfo.visible"
      v-model:showDialog="selectRepairUserInfo.visible"
      :check-box="false"
      :saveEmpty="true"
      :highlight-row="true"
      :query="selectRepairUserInfo.query"
      @callback="selectRepairUserCallBack"
    />
  </div>
</template>

<script setup name="MaintenanceOrderModify">
import { createMaintenceOrder, getRepairOrderById } from '@/api/repair'
import { getRrgUserList } from '@/api/base.js'
import PageForm from '@/components/PageForm/index'

import SelectUsers from '@/components/SelectUsers/index'
import UploadVideo from '@/components/UploadVideo/index'
import selectAsset from '@/components/SelectAsset/index'
import SelectRepairUser from '@/components/SelectUsers/selectMaintenanceUsers'
import axios from 'axios'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps(['visible', 'title', 'id', 'type', 'repairData'])

let validateExpectCompleteTime = (rule, value, callback) => {
  let faultTime = formInfo.data.faultTime
  if (faultTime) {
    if (faultTime > value) {
      callback(new Error('期望完成时间不能小于故障发生时间！'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

const action = ref(axios.defaults.baseURL + '/pub/uploadfile')
const faultTimePickerOptions = ref({})
const expectCompleteTimePickerOptions = ref({})
const options = ref([])
const formRefs = ref('')

const selectMaintenanceProvider = reactive({
  visible: false,
  query: {},
})
const selectSendOrderInfo = reactive({
  visible: false,
  saveEmpty: true,
  query: {
    orgId: '',
  },
})
const formInfo = reactive({
  baseRef: null,
  repairRef: null,
  sendOrderRef: null,
  data: {},
  formDisabled: false,
  delFiledList: [],

  baseInfoFieldList: [
    {
      label: '报修人',
      value: 'repairUserName',
      type: 'input',
      disabled: true,
    },
    {
      label: '报修部门',
      value: 'repairDeptName',
      type: 'input',
      disabled: true,
    },

    {
      label: '维修渠道',
      value: 'maintainChannel',
      type: 'select-model',
      clearable: true,
      code: 'maintain_channel',
      show: true,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 200,
    },
  ],
  repairInfoFieldList: [
    {
      label: '资产',
      value: 'assetName',
      type: 'slot',
      required: true,
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'input',
      disabled: true,
    },
    {
      label: '使用部门',
      value: 'useDeptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '位置',
      value: 'location',
      type: 'input',
      disabled: true,
    },
    {
      label: '紧急程度',
      value: 'urgencyDegree',
      type: 'radio-model',
      code: 'urgency_degree',
    },
    {
      label: '是否停机',
      value: 'isHalt',
      type: 'radio-model',
      code: 'yes_or_no',
    },
    {
      label: '故障部位',
      value: 'faultPart',
      type: 'input',
    },
    {
      label: '故障发生时间',
      value: 'faultTime',
      type: 'slot',
    },
    {
      label: '停机时长',
      value: 'expectCompleteTime',
      type: 'number',
    },

    {
      label: '故障描述',
      value: 'faultDescribe',
      type: 'textarea',
      maxlength: 500,
      required: true,
    },
    {
      label: '故障原因',
      value: 'faultReason',
      type: 'textarea',
      maxlength: 500,
    },
    {
      label: '故障图片/视频',
      value: 'filePathList',
      type: 'slot',
      className: 'not-br',
    },
  ],
  sendOrderInfoFieldList: [
    {
      label: '派单人',
      value: 'dispatchUserName',
      type: 'slot',
    },
    {
      label: '派单给',
      value: 'acceptUserName',
      type: 'slot',
    },
    {
      label: '要求完成时间',
      value: 'requireCompleteTime',
      type: 'slot',
    },
    // {
    //   label: "紧急程度",
    //   value: "urgencyDegree",
    //   type: "radio-model",
    //   code: "urgency_degree",
    // },
    {
      label: '派单说明',
      value: 'dispatchDescribe',
      type: 'textarea',
      maxlength: 255,
    },
  ],

  repairInfoRules: {
    assetName: [
      {
        required: true,
        message: '请选择资产',
        trigger: 'blur',
      },
    ],
    faultDescribe: [
      {
        required: true,
        message: '请输入故障描述',
        trigger: 'blur',
      },
    ],
    expectCompleteTime: [
      {
        validator: validateExpectCompleteTime,
        trigger: 'blur',
      },
    ],
  },
  labelWidth: '120px',
})

const fullInfo = reactive({
  btnList: [{ label: '保存', event: save, show: true }],
})
//通过资产档案新增
const selectAssetInfo = reactive({
  visible: false,
  tableKey: 'repairAddCoreAsset-com.slip.spd.entity.vo.core.CoreAssetVO',
  query: {
    queryMap: {
      // id: {
      //   queryType: "NOT_IN",
      //   queryCategory: "AND",
      //   value: "",
      // },
      status: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        // value: "2,3,4,5,6",
      },
      assetStatus: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
      isLocked: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
      // isMaintenance: {
      //   queryType: "EQUALS",
      //   queryCategory: "AND",
      //   value: 1,
      // },
      useDeptId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
      deptAuth: {
        asTbName: 'core_asset',
        columnName: 'use_dept_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'deptAuth',
      },
    },
    queryParams: {},
  },
})
//选择维修人员
const selectRepairUserInfo = reactive({
  visible: false,
  saveEmpty: true,
  query: {
    // idNotIn: "",
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
watch(
  () => formInfo.data.maintainChannel,
  (val) => {
    if (val) {
      formInfo.repairInfoFieldList[8].show = true
      formInfo.repairInfoFieldList[9].show = true
    }
  }
)
onMounted(() => {
  faultTimePickerOptions.value = {
    disabledDate(time) {
      return time.getTime() > Date.now()
    },
  }
  expectCompleteTimePickerOptions.value = {
    disabledDate(time) {
      return time.getTime() < Date.now() - 8.64e7
    },
  }

  formRefs.value = [formInfo.baseRef, formInfo.repairRef, formInfo.sendOrderRef]
  if (props.id) {
    getDetails()
  }
})

//故障图片/视频
function upload(data) {
  formInfo.data.filePathList = data
}
//资产
function callBackAsset(data) {
  selectAssetInfo.visible = false
  if (data) {
    formInfo.data['assetName'] = data.assetName
    formInfo.data['assetCode'] = data.assetCode
    formInfo.data['assetId'] = data.id
    formInfo.data['useDeptName'] = data.useDeptName
    formInfo.data['useDeptId'] = data.useDeptId
    formInfo.data['location'] = data.location
  }
}

//
function openEquipmentWindow() {
  selectAssetInfo.visible = true
}

//派单人
function openSendOrderUserList() {
  selectSendOrderInfo.visible = true
}
function openRepairUserWindow() {
  selectRepairUserInfo.visible = true
}

//选择派单人
function selectSendOrderCallBack(row) {
  if (row) {
    formInfo.data['dispatchUser'] = row.id
    formInfo.data['dispatchUserName'] = row.name
  } else {
    formInfo.data['dispatchUser'] = ''
    formInfo.data['dispatchUserName'] = ''
  }
}
//选择维修人员
function selectRepairUserCallBack(row) {
  if (row) {
    formInfo.data['acceptUser'] = row.id
    formInfo.data['acceptUserName'] = row.name
  } else {
    formInfo.data['acceptUser'] = ''
    formInfo.data['acceptUserName'] = ''
  }
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let api
    const params = {
      ...formInfo.data,
    }
    let type

    api = createMaintenceOrder
    type = 'create'
    proxy
      .$handleAPI(type, api, params)
      .then((res) => {
        if (res.success) {
          showDialog.value = false
          emit('returnModify', false)
        }
      })
      .catch(() => {})
  })
}

function getDetails() {
  getRepairOrderById(props.id).then((resp) => {
    if (resp && resp.success) {
      formInfo.data = resp.data
      formInfo.data.repairId = resp.data.id
      formInfo.data.repaidNo = resp.data.orderNo
      delete formInfo.data.id
      delete formInfo.data.orderNo
      delete formInfo.data.updateTime
      delete formInfo.data.updateUser
      delete formInfo.data.status
      delete formInfo.data.statusValue
      delete formInfo.data.updateUserName
      delete formInfo.data.version
    }
  })
}
</script>

<style scoped></style>
